<?php
namespace app\service;

use think\Db;
use app\home\model\RedEnvelope as RedEnvModel;
use app\home\model\SnatchLog;
use app\home\model\User;

/**
 * 红包服务
 */
class RedEnvelope
{
    public static $platformName     = '免死金牌';
    public static $platformId       = 0;
    public static $platformspot     = '0-9';
    /**
     * 发
     *
     * @param string $uid
     * @param string $roomId
     * @param array $data
     * @return array
     */
    public static function send($uid, $roomId, $data)
    {
        $money      = $data['money'];
        $num        = (int) $data['num'];
        
        $roomInfo   = Db::name('room')->where(['room_id' => $roomId])->find();
        $moneyRule  = explode('-', $roomInfo['gold_range']);
        $numRule    = $roomInfo['pocket'];
        $spotRule   = explode('-', static::$platformspot);
        $spot       = '';
        if ($roomInfo['type'] == 1) 
        {
            # 扫雷房间
            $spot       = (int) $data['spot'];
            if (!is_numeric($money) || $money < $moneyRule[0] || $money > $moneyRule[1]) return ['type' => 'sendResult', 'status' => 1, 'msg' => '红包金额设置不符合要求'];
            if (!is_integer($num) || $num != $numRule) return ['type' => 'sendResult', 'status' => 1, 'msg' => '红包数量设置不符合要求'];
            if ($spot < $spotRule[0] || $spot > $spotRule[1]) return ['type' => 'sendResult', 'status' => 1, 'msg' => '红包雷点设置不符合要求'];
        }
        else if ($roomInfo['type'] == 2) 
        {
            # 接龙房间
            if (!is_numeric($money) || $money < 1 || $money > 999) return ['type' => 'sendResult', 'status' => 1, 'msg' => '红包金额设置不符合要求'];
            if (!is_integer($num) || $num != $numRule) return ['type' => 'sendResult', 'status' => 1, 'msg' => '红包数量设置不符合要求'];
        }
        
        $user = User::get($uid);
        //判断余额
        if (!$user || $user->user_gold < $money) return ['type' => 'sendResult', 'status' => 1, 'msg' => '余额不足，当前账户余额 '.$user->user_gold.' 元，发包金额 '.$money.' 元'];
        //开启事务
        Db::startTrans();
        try {
            //更新余额
            $result = $user->where(['user_id' => $uid, 'user_gold' => $user->user_gold])
                ->update(['user_gold' => $user->user_gold - $money, 'update_time' => date('Y-m-d H:i:s')]);
            if (!$result) 
            {
                Db::rollback();
                return ['type' => 'sendResult', 'status' => 1, 'msg' => '数据操作失败1'];
            }
            $uName = $user->user_name ? $user->user_name : hiddenP($user->user_phone);
            $reCode = static::genRandCode();
            $redEnvModel = new RedEnvModel();
            $redEnvModel->re_code       = $reCode;
            $redEnvModel->uid           = $uid;
            $redEnvModel->room_id       = $roomId;
            $redEnvModel->money         = $money;
            $redEnvModel->num           = $num;
            $redEnvModel->left_money    = $money;
            $redEnvModel->left_num      = $num;
            $redEnvModel->uname         = $uName;
            $redEnvModel->term          = $roomInfo['term'];
            $redEnvModel->room_type     = $roomInfo['type'];
            $redEnvModel->spot          = $spot ? $spot : 0;
            $redEnvModel->status        = 0;
            $rN = $redEnvModel->save();
            $redId = $rN ? $redEnvModel->re_id : 0;
            $gType = $roomInfo['type'] ==1 ? 5 : 6;
            $gArr = [
                'user_id'       => $uid,
                'user_name'     => $uName,
                'comp_id'       => $uid,
                'room_id'       => $roomId,
                'red_id'        => $redId,
                'type'          => $gType,
                'compensation'  => -$money,
                'create_time'   => date('Y-m-d H:i:s'),
            ];
            $gN = Db::name('game_log')->insert($gArr);
            if (!$gN || !$gArr) return ['type' => 'sendResult', 'status' => 1, 'msg' => '数据操作失败33']; 
            // 提交事务
            Db::commit();
            
            return [
                'type'      => 'sendResult',
                'status'    => 0,
                'msg'       => '',
                'data'      => [
                    'reCode'    => $reCode,
                    'money'     => $money,
                    'spot'      => $spot ? $spot : 0,
                    'name'      => $uName,
                    'moneyInfo' => $user->user_gold - $money,
                    'uid'       => $uid,
                    'roomType'  => $roomInfo['type'],
                    'roomInfo'  => $roomInfo,
                    'createTime'=> time(),
                ]
            ];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            echo '异常';
            var_dump($e);
            return ['type' => 'sendResult', 'status' => 1, 'msg' => $e->getmessage()];
        }
    }

    /**
     * 生成随机字符串
     *
     * @return string
     */
    private static function genRandCode()
    {
        return substr(md5(uniqid(microtime(true),true)), 8, 16);
    }

    /**
     * 开(后期考虑使用任务投递)
     *
     * @param string $var
     * @return array
     */
    public static function open($uid, $roomId, $data)
    {
        $reCode = $data['data']['reCode'];
        if (!$reCode || !preg_match('~^[a-z0-9]{16}$~', $reCode)) {
            return ['type' => 'openResult', 'status' => 1, 'msg' => '数据格式错误'];
        }
        $redEnv = RedEnvModel::get(['re_code' => $reCode]);
        $remainTime = strtotime($redEnv->create_time)+$redEnv->term-time();
        if (!$redEnv || $redEnv->room_id != $roomId) {
            return ['type' => 'openResult', 'status' => 1, 'msg' => '红包不存在'];
        }
        if ($remainTime <= 0 && $redEnv->left_num) { return ['type' => 'openResult', 'status' => 1, 'msg' => '该红包已过期'];}
        $redEnvUser = User::get($redEnv->uid);
        $openUid    = User::get($uid);
        $roomInfo   = Db::name('room')->where(['room_id' => $roomId])->find();
        if ($roomInfo['type'] ==1) 
        {
            # 扫雷账户需要金额
            $needMoney = $redEnv->money * $roomInfo['odds'];
        }
        else if ($roomInfo['type'] ==2) 
        {
            # 接龙所需余额
            $needMoney = $roomInfo['money'];
        }
        else
        {
            return ['type' => 'openResult', 'status' => 1, '未知游戏类型'];
        }
        if ($openUid['user_gold'] < $needMoney) 
        {
            # 根据用户余额判断是否有抢包资格
            return ['type' => 'openResult', 'status' => 1, 'msg' => '余额不足，请尽快充值'];
        }
        //如果已经抢过该红包，则返回抢红包记录
        $isSnatched = SnatchLog::get(['re_id' => $redEnv->re_id, 'uid' => $uid]);
        $snatchList = [];
        // 0已抢，1未抢
        $canSnatch = $isSnatched ? 0 : $redEnv->status == 0 ? 1 : 0;
        if (!$canSnatch) {
            $snatchList = static::snatchList($redEnv->re_id); 
        }
        // $uname = $redEnvUser->user_name ? $redEnvUser->user_name : $redEnvUser->user_phone;
        $data = [
            'reCode'        =>$reCode,
            'uid'           =>$redEnv->uid,
            'sid'           =>$redEnv->uid,
            'num'           =>$redEnv->num,
            'name'          =>$redEnv->uname,
            'money'         =>$redEnv->money,
            'spot'          =>$redEnv->spot ? $redEnv->spot : 0,
            'canSnatch'     =>$canSnatch,
            'isSnatched'    =>$isSnatched?1:0,
            'snatchMoney'   =>$isSnatched?$isSnatched->money:0,
            'snatchList'    =>$snatchList
        ];

        // var_dump($data);
        return ['type' => 'openResult', 'status' => 0, 'msg' => '', 'data' => $data];
    }


    /**
     * 抢红包记录
     *
     * @param int $reId
     * @return array
     */
    private static function snatchList($reId)
    {
        // $snatchList = SnatchLog::where(['re_id' => $reId])->field('uid, money, sum, num,create_time')->limit(999)->order('sl_id', 'desc');
        $snatchList = Db::name('snatch_log')->where(['re_id' => $reId])->field('uid, name, money, sum, num, create_time')->limit(20)->order('sl_id', 'desc')->select();
        $coun = count($snatchList);
        if ($snatchList) 
        {
            if($coun != $snatchList[0]['sum'])
            {
                # 如果红包没领完隐藏平台红包
                $snatchList[$coun-1]['money'] = '***';
            }
            
        }
        else
        {
            $snatchList = [];
        }
        return $snatchList;
    }

    /**
     * 抢(只判断数据有效性)
     *
     * @param string $uid
     * @param string $fd
     * @param string $roomId
     * @param array $data
     * @return array
     */
    public static function snatch($uid, $fd, $roomId, $data)
    {
        if (array_key_exists('data', $data)) 
        {
            $reCode = $data['data']['reCode'];
            // $data['sid']    = $data['data']['uid'];
        }
        else
        {
            $reCode = $data['reCode'];
            // $data['sid']    = $data['uid'];
        }
        
        if (!$reCode || !preg_match('~^[a-z0-9]{16}$~', $reCode)) {
            return ['type' => 'snatchResult', 'status' => 1, 'msg' => '数据格式错误'];
        }
        $data['uid']    = $uid;
        $data['fd']     = $fd;
        $data['roomId'] = $roomId;
        $data['reCode'] = $reCode;
        return ['type' => 'snatchResult', 'status' => 0, 'data' => $data];
        
    }

    /**
     * 抢
     *
     * @param array $param
     * @return array
     */
    public static function doSnatch($param)
    {
        $data   = $param['data'];
        $reCode = $data['reCode'];
        $uid    = $data['uid'];
        $roomId = $data['roomId'];
        $redEnv = RedEnvModel::get(['re_code' => $reCode]);
        if (!$redEnv || $redEnv->room_id != $roomId) {
            return ['type' => 'snatchResult', 'status' => 1, 'msg' => '红包不存在'];
        }
        $redEnvUser = User::get($redEnv->uid);
        //如果已经抢过该红包，则返回
        $isSnatched = SnatchLog::get(['re_id' => $redEnv->re_id, 'uid' => $uid]);
        if ($isSnatched) {
            return ['type' => 'snatchResult', 'status' => 1, 'msg' => '您已抢过该红包--'];
        }
        //红包已抢完
        if ($redEnv->status != 0 || $redEnv->left_num == 0) {
            return ['type' => 'snatchResult', 'status' => 1, 'msg' => '红包已被抢完'];
        }

        //开启事务
        Db::startTrans();
        try {
            $randMoney = static::getRandMoney($redEnv->left_money, $redEnv->left_num);
            $leftNum = $redEnv->left_num;
            //更新剩余红包金额、数量、状态
            $result = $redEnv->where([
                    're_id'         => $redEnv->re_id,
                    'left_money'    => $redEnv->left_money,
                    'left_num'      => $redEnv->left_num,
                    'status'        => $redEnv->status])
                ->update([
                    'left_money'    => $redEnv->left_money - $randMoney,
                    'left_num'      => $redEnv->left_num - 1,
                    'status'        => $redEnv->left_num > 1 ? 0 : 1,
                    'update_time'   => date('Y-m-d H:i:s'),
                ]);
            if (!$result) {
                Db::rollback();
                return ['type' => 'snatchResult', 'status' => 1, 'msg' => '数据操作失败1'];
            }
            //抢到红包用户增加余额
            if ($uid != static::$platformId) 
            {
                # 如果当前uid为平台不进行user表操作
                $snatchUser = User::get($uid);
                $result = $snatchUser->where(['user_id' => $snatchUser->user_id, 'user_gold' => $snatchUser->user_gold])
                    ->update(['user_gold' => $snatchUser->user_gold + $randMoney]);
                if (!$result) {
                    Db::rollback();
                    return ['type' => 'snatchResult', 'status' => 1, 'msg' => $snatchUser->user_gold.'数据操作失败2'.$randMoney.'--'.$result];
                }
                $uName = $snatchUser->user_name ? $snatchUser->user_name : hiddenP($snatchUser->user_phone);
                $moneyInfo = $snatchUser->user_gold+$randMoney;
            }
            
            //添加抢红包日志
            $snatchLog = new SnatchLog();
            $snatchLog->re_id   = $redEnv->re_id;
            $snatchLog->re_code = $redEnv->re_code;
            $snatchLog->name    = isset($uName) ? $uName : static::$platformName;
            $snatchLog->uid     = $uid;
            $snatchLog->room_id = $roomId;
            $snatchLog->money   = $randMoney;
            $snatchLog->num     = $redEnv->num - $leftNum + 1;
            $snatchLog->sum     = $redEnv->num;
            $snatchLog->save();

            
            // 提交事务
            Db::commit();
            if ($uid === static::$platformId) 
            {
                # 平台直接返回
                return ['type' => 'snatchResult', 'status' => 2, 'msg' => ''];
            }
            $snatchList = static::snatchList($redEnv->re_id);

            isset($uName) ? '' : $uName=static::$platformName;
            isset($moneyInfo) ? '' : $moneyInfo=0;
            $data = [
                'reCode'        => $reCode,
                'name'          => $redEnv->uname,
                'roomId'        => $roomId,
                'money'         => $redEnv->money,
                'num'           => $redEnv->num,
                'canSnatch'     => 1,
                'isSnatched'    => 1,
                'snatchMoney'   => $randMoney,
                'snatchList'    => $snatchList,
                'snatchUser'    => $uName,
                'moneyInfo'     => $moneyInfo,
                'nextUser'      => $leftNum-1 ? 0 : 1,
                'uid'           => $uid,
                'sid'           => $redEnv->uid
            ];

            return ['type' => 'snatchResult', 'status' => 0, 'msg' => '', 'data' => $data];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['type' => 'snatchResult', 'status' => 1, 'msg' => var_export($e, true)];
        }
       
    }

    /**
     * 随机金额
     *
     * @param float $money
     * @param int $num
     * @return float
     */
    private static function getRandMoney($money, $num)
    {
        if ($num == 1) return $money;
        //随机金额在平均金额的2倍内浮动，转化为分
        $base = intval($money / $num * 200);
        $rand = mt_rand(0, $base) / 100;
        //最少1分
        if ($rand == 0) $rand = 0.01;
        //最多情况下，确保剩余其他人每人1分
        if ($rand >= $money - 0.01 * ($num - 1)) $rand = $money - 0.01 * ($num - 1);
        return $rand;
    }

    /**
     * 接龙房间开启游戏
     *  
     * @param float $money
     * @param int $num
     * @return float
     */
    public static function start($uid, $roomId)
    {
        $money  = 1; 
        $roomInfo = Db::name('room')->where(['room_id' => $roomId])->find();
        $num    = $roomInfo['pocket'];
        $name   = static::$platformName;
        $reCode         = static::genRandCode();
        $redEnvModel    = new RedEnvModel();
        $redEnvModel->re_code       = $reCode;
        $redEnvModel->uid           = static::$platformId;
        $redEnvModel->room_id       = $roomId;
        $redEnvModel->money         = $money;
        $redEnvModel->num           = $num;
        $redEnvModel->left_money    = $money;
        $redEnvModel->left_num      = $num;
        $redEnvModel->uname         = $name;
        $redEnvModel->term          = $roomInfo['term'];
        $redEnvModel->status        = 0;
        $redEnvModel->type          = 2;
        $redEnvModel->room_type     = 2;
        $redN = $redEnvModel->save();
        if ($redN) 
        {
            # 判断记录是否添加成功

            return [
                'type'      => 'startGame',
                'status'    => 0,
                'msg'       => '',
                'data'      => [
                    'reCode'    => $reCode,
                    'name'      => $name,
                    'uid'       => static::$platformId,
                    // 'moneyInfo' => $user->user_gold - $money
                ]
            ];
        }
        else
        {
            return ['type' => 'startGame', 'status' => 1, 'msg' => '数据操作失败'];
        }
    }

    /**
     * 向指定房间推送未领取红包
     *  
     * @param roomId $roomId
     * @param roomType $roomType
     * @return float
     */
    public static function pushUncollected($roomId,$roomType)
    {
        $redEnvModel    = new RedEnvModel();
        if ($roomType == 2) 
        {
            # 接龙
            $redArr = $redEnvModel->where(['room_id' => $roomId, 'status' => 0, 'room_type' => $roomType])->order('re_id','desc')->find();
            $timeout = (strtotime($redArr['create_time'])+$redArr['term'])-time();
            $redArr = $timeout > 0 ? $redArr : [];
            if ($redArr) 
            {
                return [
                        'type'      => 'pushUncollected',
                        'status'    => 0,
                        'msg'       => '',
                        'data'      => [
                                'reCode'   => $redArr['re_code'],
                                'name'     => $redArr['uname'],
                                'uid'      => $redArr['uid'],
                        ],
                    ];
            }
        }
        else if ($roomType == 1) 
        {
            # 扫雷
            $redArray = $redEnvModel->where(['room_id' => $roomId, 'status' => 0, 'room_type' => $roomType])->select();
            
            // var_dump($redArray);
            if ($redArray) 
            {
                $redArr = [];
                foreach ($redArray as $key => $value) 
                {
                    // var_dump((strtotime($value['create_time'])+$value['term'])-time());
                    if ((strtotime($value['create_time'])+$value['term'])-time() > 0) 
                    {
                        # 判断该红包是否过期
                        $redArr[] = ['reCode' => $value['re_code'],'name' => $value['uname'], 'uid' => $value['uid'],'money' => $value['money'],'spot' => $value['spot']];
                    }
                }
                $redArr = isset($redArr) ? $redArr : [];
            }
            else
            {
                $redArr = [];
            }
            if ($redArr) 
            {
                return [
                        'type'      => 'pushUncollected',
                        'status'    => 0,
                        'msg'       => '',
                        'data'      => $redArr
                    ];
            }
            else
            {
                return ['type' => 'pushUncollected','status' => 1,'msg'  => ''];
            }
        }   
        if (!isset($redArr)){return ['type' => 'pushUncollected','status' => 1,'msg'  => ''];}
    }

    /**
     * 找到抢包最小用户发包
     *  
     * @param  string   $reCode
     * @param  int      $roomId
     * @return float
     */
    public static function nextPocket($reCode,$roomId)
    {
        $snatchInfo = Db::name('snatch_log')->where(['re_code' => $reCode,'room_id' => $roomId])->where('uid','<>',0)->order('money')->find();
        // var_dump(Db::table('snatch_log')->getLastSql());
        // var_dump('发包');
        $uid = $snatchInfo['uid'];
        $roomInfo = Db::name('room')->where(['room_id' => $roomId])->find();
        $roomInfo['num'] = $roomInfo['pocket'];
        $result = static::send($uid,$roomId,$roomInfo);
        return $result;
    }

    /**
     * 判断是否中奖（后期考虑写入内存中）
     *  
     * @param  string   $snatchMoney
     * @param  int      $roomId
     * @param  int      $uid
     * @param  string   $reCode
     * @return float
     */
    public static function isPrize($snatchMoney,$roomId,$uid,$reCode)
    {
        $prizeList = Db::name('prize_rule')->where(['room_Id' => $roomId])->select();
        foreach ($prizeList as $key => $value) 
        {
            # 找到抢到金额对应的奖励
            $range = explode(',', $value['snatch_money']);
            if(in_array($snatchMoney, $range))
            {
                $prizeMoney = $value['prize_money'];
                // $prizeMoney = 1.11;
                $uN = Db::name('user')->where(['user_id' => $uid])->setInc('user_gold',$prizeMoney);
                if(!$uN) {return 0;}
                $uInfo = Db::name('user')->where(['user_id' => $uid])->find();
                $rInfo = Db::name('red_envelope')->where(['re_code' => $reCode])->find();
                # 添加抢包奖励记录
                $gameLogArr['user_id']      = $uid;
                $gameLogArr['user_name']    = $uInfo['user_name'];
                $gameLogArr['comp_id']      = $rInfo['uid'];
                $gameLogArr['room_id']      = $roomId;
                $gameLogArr['red_id']       = $rInfo['re_id'];
                $gameLogArr['type']         = 2;
                $gameLogArr['snatch_money'] = $snatchMoney;
                $gameLogArr['compensation'] = $prizeMoney;
                $gameLogArr['create_time']  = date('Y-m-d H:i:s');
                $logN    = Db::name('game_log')->insert($gameLogArr);
                if (!$logN) return 0;
                return $prizeMoney;
            }
        }
        $uInfo = Db::name('user')->where(['user_id' => $uid])->find();
        $rInfo = Db::name('red_envelope')->where(['re_code' => $reCode])->find();
        // 添加游戏记录
        $gameLogArr['user_id']      = $uid;
        $gameLogArr['user_name']    = $uInfo['user_name'];
        $gameLogArr['comp_id']      = '';
        $gameLogArr['room_id']      = $roomId;
        $gameLogArr['red_id']       = $rInfo['re_id'];
        $gameLogArr['type']         = 8;
        $gameLogArr['snatch_money'] = $snatchMoney;
        $gameLogArr['compensation'] = 0;
        $gameLogArr['create_time']  = date('Y-m-d H:i:s');
        $logN    = Db::name('game_log')->insert($gameLogArr);
        return 0;
    }

    /**
     * 判断机器人是否发包
     *  
     * @param  array    $roomInfo
     * @param  string   $reCode
     * @return array
     */
    public static function robotSend($roomInfo,$reCode)
    {
        // var_dump($roomInfo);
        $redEnvModel    = new RedEnvModel();
        $reInfo = $redEnvModel->where('room_id',$roomInfo['room_id'])->order('re_id','desc')->find();
        if(!$reInfo) return json_error('该红包不存在');
        if($reInfo['re_code'] == $reCode)
        {
            $rArr = explode(',',substr($roomInfo['robot_uid'], 1));
            shuffle($rArr);
            $uid = $rArr[1];
            $moneyRange = explode('-',$roomInfo['gold_range']);
            $money = mt_rand($moneyRange[0],$moneyRange[1]);
            $data = ['money' => $money, 'num' => $roomInfo['pocket'], 'spot' => mt_rand(0,9)];
            return self::send($uid,$roomInfo['room_id'],$data);
        }
        else
        {
            return [];
        }
    }

    /**
     * 判断机器人是否抢包
     *  
     * @param  string       $reCode
     * @param  array        $uid
     * @return array        
     */
    public static function robotSnatch($reCode,$roomInfo)
    {
        $reInfo = Db::name('red_envelope')->where('re_code',$reCode)->where('left_num','<>','0')->find();
        if (!$reInfo) return ['type' => 'robotSnatch', 'status' =>1, 'msg' => '该红包不存在']; 
        $robArr = explode(',', substr($roomInfo['robot_uid'],1));
        if ($lN = $reInfo['left_num']) 
        {
            $robotK = array_rand($robArr,$lN);
            if (is_array($robotK))
            {
                foreach($robotK as $v) $robotId[] = $robArr[$v];
            } 
            else
            {   
                $robotId[] = $robArr[$robotK];
            }
            return $data = ['reCode' => $reCode, 'uid' => $robotId, 'roomId' => $roomInfo['room_id'], 'robot' => 1, 'roomInfo' => $roomInfo];
        }
    }


    /**
     * 判断是否踩雷
     *  
     * @param  string   $snatchMoney
     * @param  int      $roomId
     * @param  int      $uid
     * @return float
     */
    public static function isStepThunder($snatchMoney,$roomId,$uid,$reCode)
    {
        $redInfo    = Db::name('red_envelope')->where(['re_code' => $reCode, 'room_id' => $roomId])->find();
        $roomInfo   = Db::name('room')->where(['room_id' => $roomId])->find();
        $spot = $redInfo['spot'];
        $snMoney = $snatchMoney * 100;
        if ((int) substr("$snMoney",-1) === $spot) 
        {
            # 匹配雷点
            if ($uid == $redInfo['uid']) 
            {
                # 自己踩自己的雷不进行数据库操作
                return ['type' => 'isStepThunder', 'status' => 0, 'msg' => '', 'data' => ['name' => $redInfo['uname']]];
            }
            $compensation   = $redInfo['money'] * $roomInfo['odds'];
            Db::startTrans();
            try 
            {
                $compN   = Db::name('user')->where(['user_id' => $uid])->setDec('user_gold',$compensation);
                $coInfo  = Db::name('user')->where(['user_id' => $uid])->find();
                $sendN   = Db::name('user')->where(['user_id' => $redInfo['uid']])->setInc('user_gold',$compensation);
                # 中雷者记录
                $gameLogArr['user_id']      = $uid;
                $gameLogArr['user_name']    = $redInfo['uname'];
                $gameLogArr['comp_id']      = $redInfo['uid'];
                $gameLogArr['room_id']      = $roomId;
                $gameLogArr['red_id']       = $redInfo['re_id'];
                $gameLogArr['type']         = 1;
                $gameLogArr['snatch_money'] = $snatchMoney;
                $gameLogArr['compensation'] = -$compensation;
                $gameLogArr['create_time']  = date('Y-m-d H:i:s');
                $logN    = Db::name('game_log')->insert($gameLogArr);

                # 发雷者记录
                $gameLogArr['user_id']      = $redInfo['uid'];
                $gameLogArr['user_name']    = $redInfo['uname'];
                $gameLogArr['comp_id']      = $uid;
                $gameLogArr['room_id']      = $roomId;
                $gameLogArr['red_id']       = $redInfo['re_id'];
                $gameLogArr['type']         = 7;
                $gameLogArr['snatch_money'] = 0;
                $gameLogArr['compensation'] = $compensation;
                $gameLogArr['create_time']  = date('Y-m-d H:i:s');
                $logN    = Db::name('game_log')->insert($gameLogArr);

                if (!$sendN || !$compN || !$logN)
                {
                    Db::rollback();
                    return ['type' => 'isStepThunder', 'status' =>1, 'msg' => '数据操作失败']; 
                }
                else
                {
                    Db::commit();
                    return ['type' => 'isStepThunder', 'status' => 0, 'msg' => '', 'data' => ['name' => $coInfo['user_name']]];
                } 

            } 
            catch (Exception $e) 
            {
                Db::rollback();
                return ['type' => 'isStepThunder', 'status' =>1, 'msg' => '数据操作失败']; 
            }
            
        }
        else
        {
            return [];
        }

    }

    /**
     * 判断发雷个数及奖励
     *  
     * @param  int      $roomId
     * @param  string   $reCode
     * @param  int      $uid
     * @param  int      $roomType
     * @return array
     */
    public static function sendThunderPrize($roomId,$reCode,$uid,$roomType)
    {
        //$snatchInfo = Db::name('snatch_log')->where(['room_id' => $roomId, 'uid' => $uid, 're_Code' => $reCode])->find();
      	$snatchInfo = Db::name('snatch_log')->where('re_Code',$reCode)->find();
        if(!$snatchInfo) { return []; }
        if ($snatchInfo['sum'] == $snatchInfo['num']) 
        {
            # 是否最后一份
            // $prizeInfo  = db('prize_rule')->where(['roomId' => $roomId, 'type' => 1])->select();
            $redInfo    = Db::name('red_envelope')->where(['room_Id' => $roomId, 're_code' => $reCode, 'room_type' => $roomType])->find();
            if(!$redInfo) { return []; }
            $snatchArr  = Db::name('snatch_log')->where(['re_code' => $reCode, 'room_Id' => $roomId])->where('uid != 0')->select();
            if(!$snatchArr) { return []; }
            $thunderNum = 0;
            foreach ($snatchArr as $key => $value) 
            {
                # 统计雷数
                if (substr($value['money'], -1) == $redInfo['spot']) 
                {
                    $thunderNum++;
                }
            }
            $prizeMoney = Db::name('prize_rule')->where(['room_Id' => $roomId, 'type' => 1, 'snatch_money' => $thunderNum])->value('prize_money');
            if(!$prizeMoney) { return []; }
            $uN = Db::name('user')->where(['user_id' => $redInfo['uid']])->setInc('user_gold',$prizeMoney);
            if(!$uN) return []; 
            $gameLogArr['user_id']             = $redInfo['uid'];
            $gameLogArr['comp_id']             = 0;
            $gameLogArr['room_id']             = $redInfo['room_id'];
            $gameLogArr['red_id']              = $redInfo['re_id'];
            $gameLogArr['type']                = 3;
            $gameLogArr['send_thunder_num']    = $thunderNum;
            // $gameLogArr['snatch_money']        = $snatchMoney;
            $gameLogArr['compensation']        = $prizeMoney;
            $gameLogArr['create_time']         = date('Y-m-d H:i:s');
            $logN    = Db::name('game_log')->insert($gameLogArr);
            if ($prizeMoney) 
            {
                # 中奖
                return [
                    'type'      => 'sendThunderPrize',
                    'status'    => 0,
                    'msg'       => '',
                    'data'      => [
                        'name'          => $redInfo['uname'],
                        'prizeMoney'    => $prizeMoney,
                        'thunderNum'    => $thunderNum
                    ]
                ];
            }
        }
        else
        {
            return [];  
        }
        
    }
}